package com.example.baiduapi.Controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.baiduapi.Util.RedisUtils;
import com.example.baiduapi.Util.StringUtils;
import com.example.baiduapi.domain.AjaxResult;
import com.example.baiduapi.domain.LoginDTO;
import com.example.baiduapi.pojo.UserInfo;
import com.example.baiduapi.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin
@Slf4j
public class LoginController {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private LoginService loginService;
    // 发送验证码
    @GetMapping("/reqMSM")
    @ResponseBody
    public AjaxResult reqMSM(String username) throws Exception {
        String s = redisUtils.get(username+"reqMSM");
        if (!StringUtils.isEmpty(s)){
            return AjaxResult.error("上个验证码还没过期呢！");
        }
        Map<String, Object> stringObjectMap = loginService.requestMessage(username);
        log.info("请求验证码返回数据为：{}",stringObjectMap);
        return AjaxResult.success("发送验证码成功");
    }
    // 登录接口
    //@InterfaceLimit(value = 50)
    @PostMapping("/Login")
    @ResponseBody
    public AjaxResult Login(@RequestBody LoginDTO loginDTO, HttpServletRequest request){
        String LoginState = "false";
        // 获取登录设备名称
        String userAgent = request.getHeader("user-agent");
        log.info("用户登录设备名称：" + userAgent);
        // 取消验证码登录
        //Messagestate = "0";
        log.info("请求地址的IP：" + getIpAddr(request));
        UserInfo user = null;
        try {
            if (loginDTO.getMessagestate().equals("1")){ // 验证码登录
                user = loginService.MessageLogin(loginDTO.getLoginName(),loginDTO.getPassword());
            }else { // 账号密码登录
                user = loginService.commOnLogin(loginDTO.getLoginName(),loginDTO.getPassword());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(ExceptionUtils.getStackTrace(e));
            log.info("登录失败！，异常信息为：{}",e);
        }
        if (user != null){
            // 使用 sa-token 进行登录，传入用户ID
            StpUtil.login(user.getId());
            // 获取 token
            String token = StpUtil.getTokenValue();
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            data.put("token", token);
            log.info("用户 {} 登录成功，token: {}", user.getId(), token);
            return AjaxResult.success("登录成功！", data);
        }else {
            return AjaxResult.error("账号都登不上，不如去玩原神！");
        }
    }

    // 登出接口
    @PostMapping("/Logout")
    @ResponseBody
    public AjaxResult logout(){
        try {
            StpUtil.logout();
            log.info("用户登出成功");
            return AjaxResult.success("登出成功！");
        } catch (Exception e) {
            log.error("登出失败：{}", e.getMessage());
            return AjaxResult.error("登出失败！");
        }
    }

    public String getIpAddr(HttpServletRequest request){
        String ipAddress = null;

        try {
            ipAddress = request.getHeader("x-forwarded-for");

            if (ipAddress == null || ipAddress.length() == 0) {
                String[] altHeaders = {"Proxy-Client-IP", "WL-Proxy-Client-IP"};

                for (String header : altHeaders) {
                    ipAddress = request.getHeader(header);

                    if (ipAddress != null && ipAddress.length() != 0) {
                        break;
                    }
                }
            }

            if (ipAddress == null) {
                ipAddress = request.getRemoteAddr();

                if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                    ipAddress = "";
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }



        return ipAddress;
    }

}
